from langchain_core.documents import Document
from langchain_core.tools import tool
from patagent.constant import *

try:
    from atlassian import Confluence, Jira
except ImportError:
    raise ImportError(
        "atlassian-python-api is not installed. "
        "Please install it with `pip install atlassian-python-api`"
    )


jira = Jira(
    url=JIRA_URL,
    username=JIRA_USERNAME,
    password=JIRA_TOKEN,
)

@tool
def load_jira_documents_project(project):
    """parse jira tickets with a project name"""
    JQL = JQL_TEMPLATE.format(project=project)
    issue_count = jira.jql(JQL, fields="*none")["total"]
    docs = []
    for i in range(0, issue_count, JIRA_BATCH):
        issues = jira.jql(JQL, fields='*all', start=i, limit=JIRA_BATCH)["issues"]
        for issue in issues:
            client_name = issue['fields']['customfield_10302']
            description = issue['fields']['description']
            solution = issue['fields']['customfield_11621']
            root_cause = issue['fields']['customfield_11620']
            qa = [p['displayName'] for p in issue['fields']['customfield_12216']] if issue['fields']['customfield_12216'] is not None else None
            pm = issue['fields']['customfield_11941']['displayName'] if issue['fields']['customfield_11941'] is not None else None
            assignee = issue['fields']['assignee']['displayName']if issue['fields']['assignee'] is not None else None
            attachment = [{'content': a['content'], 'filename': a['filename'], 'created': a['created'], 'size': a['size'], 'mimeType': a['mimeType']} for a in issue['fields']['attachment']] if issue['fields']['attachment'] is not None else None
            
            docs.append({
                "content": '客户名称：{client_name}\n\n问题描述：{description}\n\n解决方案：{solution}\n\n问题原因：{root_cause}'.format(client_name=client_name, description=description, solution=solution, root_cause=root_cause),
                "metadata": {'url': issue['self'], 'key': issue['key'], 'qa': qa, 'pm': pm, 'assignee': assignee, 'attachment': attachment},
            })
    return docs
